<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-5-3
 * Time: 下午2:32
 */

namespace console\modules\loan\controllers;


use common\components\loan\RongYiXing;
use common\components\tools\FileHelper;
use common\components\tools\Tools;
use common\models\LoanApplyImagesUpload;
use yii\base\ErrorException;
use yii\console\Controller;

class DefaultController extends Controller
{
    /**
     * php yii loan/default/ryx-images-upload
     * @throws ErrorException
     */
    public function actionRyxImagesUpload()
    {
        $un_upload_images = LoanApplyImagesUpload::find()->where(['company_code'=>RongYiXing::COMPANY_CODE, 'status'=>LoanApplyImagesUpload::STATUS_NO_UPLOAD])->all();
        $sftp_ryx = \Yii::$app->sftp_ryx;
        foreach ($un_upload_images as $k => $v){
            $bool = 1;
            $images = unserialize($v->images);
            $dir_m = substr($v->loan_date, 0, 6);
            $dir_d = substr($v->loan_date, 6, 2);
            $dir = $dir_m.DIRECTORY_SEPARATOR.$dir_d.DIRECTORY_SEPARATOR.$v->loan_code;
            if ($sftp_ryx->has($dir)){
                $bool *= $sftp_ryx->deleteDir($dir);
            }
            $bool *= $sftp_ryx->createDir($dir);
            foreach ($images as $k1 => $v1) {
                if (is_array($v1)){
                    foreach ($v1 as $k2 => $v2){
                        $bool *= $sftp_ryx->put($dir.DIRECTORY_SEPARATOR.$k1.$k2.".".FileHelper::getExtensionName1($v2), file_get_contents($v2));
                    }
                }
            }
            if ($bool){
                $v->status = LoanApplyImagesUpload::STATUS_UPLOADED;
                $v->uploaded_at = time();
                if ($v->save()){
                    echo "saved ";
                }else{
                    throw new ErrorException("保存异常");
                }
            }
        }
    }
}